$(function () {
    let $con = $(".hot_list")
    function init() {

        load()
            .done(function (res) {
                render(res.list)
                handlerAddCart()
            })

    }

    function load() {

        let options = {
            url: "../../static/libs/json/prototype.json",
            dataType: "json"
        }

        return $.ajax(options)

    }

    function render(res) {
        $con.html(res.map(item =>
            `
        <li>
            <a href="./datails.html#id=${item.id}">
            <img src="${item.img}" alt="">
            <div class="li_msg">
                <h3>${item.name}</h3>
                <p>${item.title}</p>
                <span>${item.price}</span>
            </div>
            </a>
            <div class="top_right" data-id="${item.goods_id}">
            <span>加入购物车</span>
        </div>
        </li>
        `
        ))
    }

    function handlerAddCart() {

        $(".top_right").click(function () {

            let user_id = getCookie("userid");
            let goods_id = $(this).attr("data-id");
            let token = getCookie("token");

            var options = {
                url: `http://127.0.0.1:8888/cart/add?id=${user_id}&goodsId=${goods_id}`,
                type: "post",
                data: {
                    id: user_id,
                    goodsId: goods_id
                },
                headers: {
                    authorization: token
                }
            }

            $.ajax(options)
                .done(function (data) {
                    console.log( data );
                    handlerAjax(data);
                });


            function handlerAjax(data) {
                switch (data.code) {
                    case 1:
                        alert(data.message);
                        break;
                    case 401:
                        alert("抱歉您还没有登录，请登录后再去加入购物车");
                        location.href = "./login.html#goods";
                        break;
                }
            }

        })

    }

    init()
})